// 抛出错误的包
const assert = require("http-assert")
// 设置token的包
const jwt = require('jsonwebtoken')
// 引入自定义的秘钥 设置和解密token的
const {SecretKey} = require('../SecretKey')
// 引入模型
const AdminUser = require('../models/AdminUser')

module.exports = () => (async (req, res, next) => {
  const token = String(req.headers.authorization || '').split(' ').pop();
  assert(token, 401, '请登录')
  // 验证token
  const tokenData = jwt.verify(token, SecretKey)
  const { id } = tokenData;
  assert(id, 401, '请重新登录')
  req.user = await AdminUser.findById(id)
  assert(req.user, 401, '请重新登录')
  // console.log('id',req.user.username)
  // console.log('tokenData:',tokenData)
  await next()
})